package cn.hunqing.web.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import cn.hunqing.web.msg.LoginMsgs;
import cn.hunqing.web.param.AbstractParameters;
import cn.hunqing.web.param.LoginParameters;
import cn.hunqing.web.service.UserService;
import cn.hunqing.web.session.SessionUserInfo;
import cn.hunqing.web.util.PathConstants;
import cn.hunqing.web.util.SessionUtils;
import cn.hunqing.web.util.ViewConstants;

/**
 * add the redirect method
 * 
 * @date 2015-07-27 21:12
 */
@Controller
@RequestMapping(PathConstants.PATH_LOGIN)
public class LoginController {
	private static Logger logger = LoggerFactory.getLogger(LoginController.class);

	@Autowired
	private UserService userService;
	
	@RequestMapping(method = RequestMethod.GET)
	public String doGet(HttpServletRequest request, HttpServletResponse response, ModelMap model) {
		logger.info("Get the login request，contextPath:", request.getContextPath());
		model.addAttribute(LoginParameters.RESPONSE_USERACCOUNT, "test");
		return ViewConstants.VIEW_LOGIN;
	}

	@RequestMapping(method = RequestMethod.POST)
	public String doPost(HttpServletRequest request, HttpServletResponse response, HttpSession httpSession,
			ModelMap model) {
		logger.info("Get the login request");
		// SessionUtils.doLogin(httpSession, new SessionUserInfo());
		// step 1, check user from email or phone or userName
		String userName = request.getParameter(LoginParameters.REQUEST_USERNAME);
		String password = request.getParameter(LoginParameters.REQUEST_PASSWORD);
		userName = StringUtils.trim(userName);
		SessionUserInfo	user = userService.findByUserNameAndPassword(userName, password);
		
		// login successfully
		if (user != null) {
			logger.info("{} login system sucessfully!",userName);
			SessionUtils.doLogin(request.getSession(), user);

			Object redirectFrom = httpSession.getAttribute(LoginParameters.REDRIECT_FROM);
			if(redirectFrom != null && redirectFrom instanceof String){
				httpSession.removeAttribute(LoginParameters.REDRIECT_FROM);
				return "redirect:"+(String)redirectFrom;
			}else{
				return PathConstants.REDIRECT_TEMPLATE_LIST+"/v2";
			}
		} else {
			logger.info("{} login system failed!",userName);
			model.addAttribute(AbstractParameters.RESPONSE_ERROR_MSG, LoginMsgs.WRONG_USERNAME_PASSWORD);
			return PathConstants.PATH_LOGIN;
		}
	}

}
